import { DatePicker, Input } from '@/components/AntdProxy';
import CommonDrawer from '@/components/CommonDrawer';
import CommonTable from '@/components/CommonTable';
import { CrudFormLayout } from '@/components/Crud';
import { LineSelect } from '@/components/CustomForm';
import { REQUIRED } from '@/constants/rules';
import request from '@/utils/request';
import { useAsyncEffect } from 'ahooks';
import { Form, message } from 'antd';
import dayjs from 'dayjs';
import { useState } from 'react';
const Save = (props) => {
  const { open, record, onCancel, onOk } = props;
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [weightData, setWeightData] = useState([]);
  const [form] = Form.useForm();
  useAsyncEffect(async () => {
    if (open && record) {
      // 查询结算单详情
      const res = await request({
        url: '/datas/settlement/detail',
        method: 'GET',
        params: {
          settlementId: record.settlementId,
        },
      });
      console.log('---res.settlement', res.settlement);
      setWeightData(res.weights);
      setSelectedKeys(
        res.weights
          .filter((item) => item.settlementState === 1)
          .map((item) => item.weightId),
      );
      form.setFieldsValue({
        ...res.settlement,
        fromTime: res.settlement.fromDate
          ? dayjs(res.settlement.fromDate)
          : undefined,
        toTime: res.settlement.toDate
          ? dayjs(res.settlement.toDate)
          : undefined,
        day: res.settlement.day ? dayjs(res.settlement.day) : undefined,
      });
    }
  }, [open, record]);

  const handleOk = async () => {
    const values = await form.validateFields();
    console.log('values', values);
    if (!selectedKeys.length) {
      message.warning('请选择榜单数据');
      return;
    }
    const url = record ? '/datas/settlement/update' : '/datas/settlement/add';
    const params = {
      ...values,
      weightIds: selectedKeys,
      fromDate: values.fromTime
        ? dayjs(values.fromTime).format('YYYY-MM-DD')
        : undefined,
      toDate: values.toTime
        ? dayjs(values.toTime).format('YYYY-MM-DD')
        : undefined,
      day: values.day ? dayjs(values.day).format('YYYY-MM-DD') : undefined,
    };
    if (record) {
      params.settlementId = record?.settlementId;
    }
    await request({
      url,
      method: 'POST',
      data: params,
    });
    message.success('操作成功');
    onOk?.();
  };
  const columns = [
    {
      title: '装车磅单号',
      dataIndex: 'loadWeightCode',
      width: 150,
    },
    {
      title: '装车净重',
      dataIndex: 'loadWeight',
      width: 150,
    },
    {
      title: '装车时间',
      dataIndex: 'loadTime',
      width: 150,
    },
    {
      title: '卸车磅单号',
      dataIndex: 'unloadWeightCode',
      width: 150,
    },
    {
      title: '卸车净重',
      dataIndex: 'unloadWeight',
      width: 150,
    },
    {
      title: '卸车时间',
      dataIndex: 'unloadTime',
      width: 150,
    },
    {
      title: '任务营收',
      dataIndex: 'taskPrice',
      width: 150,
    },
    {
      title: '车牌号',
      dataIndex: 'license',
      width: 150,
    },
    {
      title: '装货司机',
      dataIndex: 'loadDriver',
      width: 150,
    },
    {
      title: '卸货司机',
      dataIndex: 'unloadDriver',
      width: 150,
    },
  ];
  const handleFormValueChange = async (changedValues) => {
    if (
      changedValues.fromTime ||
      changedValues.toTime ||
      changedValues.lineId
    ) {
      const params = form.getFieldsValue();
      if (params.lineId && params.fromTime && params.toTime) {
        const res = await request({
          url: '/datas/settlement/none/weight/list',
          method: 'GET',
          params: {
            ...params,
            fromTime: dayjs(params.fromTime).format('YYYY-MM-DD'),
            toTime: dayjs(params.toTime).format('YYYY-MM-DD'),
            index: 0,
            size: 0,
          },
        });
        setWeightData(res);
      }
    }
  };

  return (
    <CommonDrawer
      title={record ? '编辑' : '新建'}
      open={open}
      onClose={onCancel}
      onOk={handleOk}
      afterOpenChange={(visible) => {
        if (!visible) {
          form.resetFields();
        }
      }}
      width={800}
      destroyOnHidden
    >
      <Form
        form={form}
        layout="vertical"
        onValuesChange={handleFormValueChange}
      >
        <CrudFormLayout itemMinWidth={250}>
          <Form.Item label="线路名称" name="lineId" rules={[REQUIRED]}>
            <LineSelect />
          </Form.Item>
          <Form.Item label="标题" name="title" rules={[REQUIRED]}>
            <Input placeholder="请输入标题" />
          </Form.Item>
          <Form.Item label="结算日期" name="day">
            <DatePicker placeholder="请选择结算日期" />
          </Form.Item>
          <Form.Item label="开始日期" name="fromTime" rules={[REQUIRED]}>
            <DatePicker placeholder="请选择开始日期" />
          </Form.Item>
          <Form.Item label="结束日期" name="toTime" rules={[REQUIRED]}>
            <DatePicker placeholder="请选择结束日期" />
          </Form.Item>
          <Form.Item label="总金额" name="totalPrice">
            <Input placeholder="请输入总金额" disabled />
          </Form.Item>
        </CrudFormLayout>
        <Form.Item label="备注" name="remark">
          <Input.TextArea maxLength={150} />
        </Form.Item>
        <CommonTable
          dataSource={weightData}
          rowKey="weightId"
          columns={columns}
          pagination={false}
          rowSelection={{
            selectedRowKeys: selectedKeys,
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedKeys(selectedRowKeys);
              // 计算总金额
              form.setFieldValue(
                'totalPrice',
                selectedRows.reduce((a, b) => {
                  return a + b.taskPrice;
                }, 0),
              );
            },
          }}
        />
      </Form>
    </CommonDrawer>
  );
};

export default Save;
